﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MADSite.Account
{
  public partial class Login : System.Web.UI.Page
  {
    private int id = -1;
    TrainManagerClient trainManagerClient = new TrainManagerClient();
    
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Request.Cookies.AllKeys.Contains("id"))
      {
        id = trainManagerClient.InitUser();
      }
      else
      {
        id = Int32.Parse(Request.Cookies["id"].Value);
      }
      HttpCookie cook = new HttpCookie("id", id.ToString());
      Response.Cookies.Add(cook);
      //HttpCookie cookie = Request.Cookies["tries"];
      //if (cookie != null)
      //{
      //  RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
      //  if (RegisterHyperLink.NavigateUrl == "Register.aspx?ReturnUrl=" | RegisterHyperLink.NavigateUrl == "Register.aspx?ReturnUrl=%2fAccount%2fBotChecker.aspx")
      //  {
      //    if (cookie.Value == "3")
      //    {
      //      Response.Redirect("~/BotChecker.aspx");
      //    }
      //    else
      //    {
      //      Response.Cookies["tries"].Value = (Int32.Parse(cookie.Value) + 1).ToString();
      //    }
      //  }
      //}
      //else
      //{
      //  RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
      //  if (RegisterHyperLink.NavigateUrl == "Register.aspx?ReturnUrl=")
      //  {
      //    HttpCookie tryCookie = new HttpCookie("tries");
      //    tryCookie.Value = "0";
      //    tryCookie.Expires = DateTime.Now.AddDays(1);
      //    Response.Cookies.Add(tryCookie);
      //  }
      //}
    }

    protected void LoginButton_Click(object sender, EventArgs e)
    {
      bool isBot = false;
      bool succeed = trainManagerClient.Login(out isBot, id, 
        LoginUser.UserName, LoginUser.Password);
      //HttpCookie cookie = Request.Cookies["tries"];
      if (!succeed)
      {
        //RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        //if (!succeed)
        //{
          if (isBot)
          {
            Response.Redirect("~/BotChecker.aspx");
          }
          //else
          //{
          //  Response.Cookies["tries"].Value = (Int32.Parse(cookie.Value) + 1).ToString();
          //}
        //}
      }
      else
      {
        RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        if (RegisterHyperLink.NavigateUrl == "Register.aspx?ReturnUrl=")
        {
          HttpCookie tryCookie = new HttpCookie("tries");
          tryCookie.Value = "0";
          tryCookie.Expires = DateTime.Now.AddDays(1);
          Response.Cookies.Add(tryCookie);
        }
      }
    }
  }
}
